package cn.edu.njust.alg.leetcode;

public class Leetcode_38_count_and_say {

	/*
	 * 
	 * The count-and-say sequence is the sequence of integers beginning as
	 * follows: 1, 11, 21, 1211, 111221, ...
	 * 
	 * 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is
	 * read off as "one 2, then one 1" or 1211. Given an integer n, generate the
	 * nth sequence.
	 * 
	 * Note: The sequence of integers will be represented as a string.
	 */

	public static String countAndSay(int n) {

		String string = "1";
		for (int i = 1; i < n; i++) {
			string = nextString(string);
		}
		return string;

	}

	public static String nextString(String s) {
		StringBuffer sb = new StringBuffer();
		int i, j;
		for (i = 0; i < s.length(); i++) {
			for (j = i + 1; j < s.length(); j++) {
				if (s.charAt(i) != s.charAt(j)) {
					break;
				}
			}
			sb.append(String.valueOf(j - i));
			sb.append(s.charAt(i));
			i = --j;
		}
		return sb.toString();
	}

	public static void main(String[] args) {


			System.out.println(countAndSay(6));

	}

}
